#!/usr/bin/env bun

import { exists, readdir, rm } from 'node:fs/promises';
import { join } from 'node:path';
import readline from 'readline';

import { $ } from 'bun';

console.log('🚀 欢迎使用项目初始化工具！\n');

// 递归遍历目录并替换文件内容
const replaceInDirectory = async (
  dir: string,
  search: string,
  replace: string
): Promise<number> => {
  let count = 0;
  const entries = await readdir(dir, { withFileTypes: true });

  const promises: Promise<void>[] = [];
  for (const entry of entries) {
    const fullPath = join(dir, entry.name);

    if (entry.isDirectory()) {
      // 递归处理子目录
      promises.push(
        (async (): Promise<void> => {
          count += await replaceInDirectory(fullPath, search, replace);
        })()
      );
    } else if (entry.isFile()) {
      promises.push(
        (async (): Promise<void> => {
          try {
            const file = Bun.file(fullPath);
            const content = await file.text();

            // 如果文件内容包含搜索字符串，则替换
            if (content.includes(search)) {
              const updatedContent = content.replace(new RegExp(search, 'g'), replace);
              await file.write(updatedContent);
              count++;
            }
          } catch {
            // 跳过无法读取的文件（如二进制文件）
          }
        })()
      );
    }
  }

  await Promise.all(promises);

  return count;
};

// 原生交互式获取输入
const readInput = async (prompt: string, required = false): Promise<string> => {
  return new Promise(resolve => {
    const rl = readline.createInterface({
      input: process.stdin,
      output: process.stdout,
    });

    const ask = () => {
      rl.question(prompt, input => {
        const trimmed = input.trim();
        if (required && !trimmed) {
          console.log('❌ 此项为必填项，请重新输入');
          ask();
        } else {
          rl.close();
          resolve(trimmed);
        }
      });
    };

    ask();
  });
};

// 获取项目信息
const name = await readInput('🏷️ 请输入项目名称: ', true);
const description = await readInput('📝 请输入项目描述: ', true);
const version = (await readInput('🔢 请输入项目版本号 (默认: 1.0.0): ')) || '1.0.0';
const author = await readInput('👤 请输入作者名称: ');

console.log('\n📋 项目信息确认:');
console.log(`   名称: ${name}`);
console.log(`   描述: ${description}`);
console.log(`   版本: ${version}`);
console.log(`   作者: ${author ?? '未设置'}`);

console.log('\n🔄 开始初始化项目配置...\n');

// 1. 更新 package.json
const packageFile = Bun.file('package.json');
const packageJson = JSON.parse(await packageFile.text());
packageJson.name = name.toLowerCase().replace(/\s+/g, '-');
packageJson.description = description;
packageJson.version = version;
if (author) {
  packageJson.author = author;
}
await packageFile.write(JSON.stringify(packageJson, null, 2) + '\n');
console.log('📦 已更新 package.json');

// 2. 更新 LICENSE 文件
const licenseFile = Bun.file('LICENSE');
if (await licenseFile.exists()) {
  const licenseContent = await licenseFile.text();
  const updatedLicense = licenseContent.replace(
    /Copyright \(c\) \d{4} [^\n]*/,
    `Copyright (c) ${new Date().getFullYear()} ${name}`
  );
  await licenseFile.write(updatedLicense);
  console.log('📄 已更新 LICENSE 文件');
}

// 3. 更新 helm/Chart.yaml（精确更新）
const projectSlug = name.toLowerCase().replace(/\s+/g, '-');
const chartFile = Bun.file('helm/Chart.yaml');
if (await chartFile.exists()) {
  const chartContent = await chartFile.text();
  const updatedChart = chartContent
    .replace(/^name: .+$/m, `name: ${projectSlug}`)
    .replace(/^description: .+$/m, `description: ${description}`)
    .replace(/^version: .+$/m, `version: ${version}`)
    .replace(/^appVersion: .+$/m, `appVersion: '${version}'`)
    .replace(/^  - name: .+$/m, author ? `  - name: ${author}` : '  - name: ');
  await chartFile.write(updatedChart);
  console.log('⚓ 已更新 helm/Chart.yaml');
}

// 4. 更新配置模式文件
const configSchemaFile = Bun.file('src/config/schema.ts');
if (await configSchemaFile.exists()) {
  const configSchemaContent = await configSchemaFile.text();
  const updatedConfigSchema = configSchemaContent
    .replace(
      /APP_NAME: z\.string\(\)\.default\('[^']*'\)/,
      `APP_NAME: z.string().default('${name}')`
    )
    .replace(
      /APP_VERSION: z\.string\(\)\.default\('[^']*'\)/,
      `APP_VERSION: z.string().default('${version}')`
    )
    .replace(
      /APP_DESCRIPTION: z\s*\.string\(\)\s*\.default\('[^']*'\)/,
      `APP_DESCRIPTION: z.string().default('${description}')`
    );
  await configSchemaFile.write(updatedConfigSchema);
  console.log('⚙️  已更新配置模式文件');
}

// 5. 更新 helm 目录下的其他文件（批量替换项目名）
if (await exists('helm')) {
  const helmUpdateCount = await replaceInDirectory('helm', 'elysia-demo', projectSlug);
  console.log(`⚓ 已批量更新 helm 目录下的 ${helmUpdateCount} 个文件`);
}

// 6. 删除 README.md
await rm('README.md');

// 7. 重新初始化Git仓库
if (await exists('.git')) {
  await rm('.git', { recursive: true, force: true });
  console.log('🗑️  已删除现有Git仓库');
}
await $`git init`;
console.log('🌱 已初始化新的Git仓库');

// 8. 安装依赖
console.log('\n📦 开始安装项目依赖...');
try {
  await $`bun install`;
  console.log('✅ 依赖安装完成');
} catch {
  console.log('⚠️  依赖安装失败，请手动运行: bun install');
}

console.log('\n🎉 项目初始化完成！');
console.log('\n🔧 已完成的操作:');
console.log('   ✓ 更新 package.json');
console.log('   ✓ 更新 LICENSE 文件');
console.log('   ✓ 更新 helm/Chart.yaml');
console.log('   ✓ 更新配置模式文件');
console.log('   ✓ 更新 helm 模板文件');
console.log('   ✓ 删除 README.md');
console.log('   ✓ 重新初始化Git仓库');
console.log('   ✓ 安装项目依赖');
